<script setup lang="ts">
/* 学习目标：完成绑定手机号码  */
// 1. 封装绑定的API
import { bindMobileAPI, loginByQQAPI, sendCodeAPI } from '@/services/user'
import { useUserStore } from '@/stores'
import { codeRules, mobileRules } from '@/utils/rules'
import { showToast } from 'vant'
import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const mobile = ref('13230000001')
const code = ref('')
const second = ref(0)

let timerId: number
const onSendCode = async () => {
  const res = await sendCodeAPI(mobile.value, 'bindMobile')
  code.value = res.data.code
  second.value = 60
  timerId = setInterval(() => {
    second.value--
    if (second.value === 0) clearInterval(timerId)
  }, 100)
}

onUnmounted(() => {
  clearInterval(timerId)
})

const openId = ref('')
const needBind = ref(false)
const store = useUserStore()
const router = useRouter()
onMounted(() => {
  if (window.QC.Login.check()) {
    window.QC.Login.getMe((id: string) => {
      // 2. 声明openId，保存openId
      openId.value = id
      loginByQQAPI(id)
        .then(({ data }) => {
          // 5.2 处理已绑定手机号的成功逻辑
          onSuccess(data)
        })
        .catch(() => {
          needBind.value = true
        })
    })
  }
})

// 4. 封装处理登录成功后的逻辑
const onSuccess = (data: any) => {
  store.saveUser(data)
  router.push('/')
  showToast('登录成功')
}

const onSubmit = async () => {
  // 3. 调用绑定手机号的接口
  const { data } = await bindMobileAPI({
    mobile: mobile.value,
    code: code.value,
    openId: openId.value
  })
  // 5.1 处理绑定手机号的成功
  onSuccess(data)
}
</script>

<template>
  <div class="login-page" v-if="needBind">
    <cp-nav-bar title="绑定手机号"></cp-nav-bar>

    <van-form autocomplete="off" @submit="onSubmit">
      <van-field v-model="mobile" placeholder="请输入手机号" type="tel" :rules="mobileRules" />

      <van-field :rules="codeRules" v-model="code" placeholder="请输入验证码">
        <template #button>
          <span class="send-code" v-show="second === 0" @click="onSendCode">发送验证码</span>
          <span v-show="second > 0">{{ second }}秒后获取</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"> 立即绑定 </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .send-code {
    --cp-primary: #16c2a3;
    color: var(--cp-primary);
  }
}
</style>
